<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>在线考试系统 - 学生考试界面</title>
    <!-- 引入静态资源 -->
    <link rel="stylesheet" href="static/index.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/index.js"></script>
    <script src="static/axios.min.js"></script>
    <!-- 自定义样式 -->
    <style>
        body {
            background-color: #f0f2f5;
            font-family: 'Microsoft YaHei', sans-serif;
        }

        .exam-container {
            max-width: 900px;
            margin: 20px auto;
            background-color: #fff;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        }

        .question {
            margin-bottom: 30px;
        }

        .question-title {
            font-size: 18px;
            font-weight: bold;
        }

        .options {
            margin-top: 10px;
        }

        .options .el-radio {
            display: block;
            margin-bottom: 10px;
        }

        .submit-btn {
            text-align: center;
            margin-top: 40px;
        }

        .timer {
            position: fixed;
            top: 20px;
            right: 20px;
            font-size: 18px;
            color: #f56c6c;
        }

        .paper-list {
            max-width: 1200px;
            margin: 20px auto;
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
        }

        .paper-item {
            flex: 1 1 calc(33.333% - 20px);
            box-sizing: border-box;
            padding: 20px;
            background-color: #fff;
            border-radius: 12px;
            border: 1px solid #ebeef5;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: transform 0.3s, box-shadow 0.3s;
            position: relative;
            overflow: hidden;
        }

        .paper-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 14px rgba(0,0,0,0.1);
        }

        .paper-title {
            font-size: 20px;
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }

        .paper-title::before {
            content: '📄';
            margin-right: 8px;
        }

        .paper-info {
            margin-top: 10px;
            color: #666;
            line-height: 1.6;
        }

        .start-exam-btn {
            text-align: center;
            margin-top: 15px;
        }

        .correct-answer {
            margin-top: 10px;
            color: #409EFF;
        }

        .search-bar {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }

        .no-papers {
            text-align: center;
            font-size: 18px;
            color: #909399;
            margin-top: 50px;
        }

        @media screen and (max-width: 1024px) {
            .paper-item {
                flex: 1 1 calc(50% - 20px);
            }
        }

        @media screen and (max-width: 768px) {
            .paper-item {
                flex: 1 1 100%;
            }
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 考试倒计时 -->
    <div class="timer" v-if="remainingTime > 0">
        ⏰ 考试倒计时：{{ formatTime(remainingTime) }}
    </div>

    <!-- 选择试卷界面 -->
    <div v-if="!paper && !isExamStarted && !isExamReview">
        <div class="search-bar">
            <el-input
                    placeholder="🔍 搜索试卷名称"
                    v-model="searchKeyword"
                    style="width: 300px;"
                    @input="handleSearch"
                    clearable>
            </el-input>
        </div>
        <div class="paper-list">
            <div v-for="paper in availablePapers" :key="paper.paperId" class="paper-item">
                <div>
                    <div class="paper-title">{{ paper.paperName }}</div>
                    <div class="paper-info">
                        ⏳ 考试时长：{{ paper.duration }}分钟<br>
                        🎯 总分：{{ paper.totalScore }}分
                    </div>
                </div>
                <!-- 如果已经考过，显示分数和查看按钮 -->
                <div v-if="examRecords[paper.paperId]">
                    <div class="paper-info" style="color: #67c23a;">
                        🏆 已考，得分：{{ examRecords[paper.paperId].score }}分
                    </div>
                    <div class="start-exam-btn">
                        <el-button type="primary" @click="viewExam(examRecords[paper.paperId])">📖 查看试卷</el-button>
                    </div>
                </div>
                <!-- 否则显示开始考试按钮 -->
                <div v-else class="start-exam-btn">
                    <el-button type="success" @click="startExam(paper.paperId)">🎬 开始考试</el-button>
                </div>
            </div>
            <!-- 如果没有试卷 -->
            <div v-if="availablePapers.length === 0" class="no-papers">
                😞 暂无可用试卷，请联系管理员。
            </div>
        </div>
        <!-- 分页 -->
        <div style="text-align: center; margin-top: 20px; width: 100%;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[6, 12, 18]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </div>

    <!-- 考试界面 -->
    <div v-if="(paper && isExamStarted) || isExamReview" class="exam-container">
        <h2 style="text-align: center;">{{ paper.paperName }}</h2>
        <div style="text-align: center; margin-bottom: 20px;">
            ⏳ 考试时长：{{ paper.duration }}分钟&nbsp;&nbsp;&nbsp;&nbsp;🎯 总分：{{ paper.totalScore }}分
        </div>
        <div v-if="paper.description" style="margin-bottom: 20px;">
            <el-alert
                    title="📢 考试说明"
                    type="info"
                    :description="paper.description"
                    show-icon>
            </el-alert>
        </div>
        <el-form :model="answers">
            <div v-for="(question, index) in questions" :key="question.questionId" class="question">
                <div class="question-title">
                    {{ index + 1 }}. {{ question.title }}
                </div>
                <div class="options">
                    <el-radio-group v-model="answers[question.questionId]" :disabled="isExamReview">
                        <el-radio :label="'A'">{{ question.optionA }}</el-radio>
                        <el-radio :label="'B'">{{ question.optionB }}</el-radio>
                        <el-radio :label="'C'">{{ question.optionC }}</el-radio>
                        <el-radio :label="'D'">{{ question.optionD }}</el-radio>
                    </el-radio-group>
                </div>
                <!-- 如果是在查看考试回顾，显示正确答案 -->
                <div v-if="isExamReview" class="correct-answer">
                    正确答案：{{ question.correctAnswer }}
                    <span v-if="answers[question.questionId] === question.correctAnswer" style="color: #67c23a;">✔️ 回答正确</span>
                    <span v-else style="color: #f56c6c;">❌ 回答错误</span>
                </div>
            </div>
        </el-form>
        <div class="submit-btn" v-if="!isExamReview">
            <el-button type="primary" size="large" @click="submitExam">💾 提交考试</el-button>
        </div>
        <!-- 添加返回按钮 -->
        <div class="submit-btn" v-if="isExamReview">
            <el-button size="large" @click="backToPaperList">🔙 返回试卷列表</el-button>
        </div>
    </div>
</div>

<!-- 前端逻辑 -->
<script>
    new Vue({
        el: '#app',
        data: {
            user: null,             // 当前用户信息
            paper: null,            // 当前试卷信息
            questions: [],          // 当前试卷的题目列表
            answers: {},            // 学生的答案
            remainingTime: 0,       // 剩余时间（秒）
            timerInterval: null,    // 定时器
            availablePapers: [],    // 可用试卷列表
            examRecords: {},        // 考试记录，key为paperId
            isExamStarted: false,   // 是否已开始考试
            isExamReview: false,    // 是否在查看考试回顾
            currentPage: 1,         // 当前页码
            pageSize: 6,            // 每页显示条数
            total: 0,               // 总记录数
            searchKeyword: ''       // 搜索关键词
        },
        methods: {
            // 加载可用试卷列表
            async loadAvailablePapers() {
                try {
                    const response = await axios.get('/paper', {
                        params: {
                            operation: 'findPage',
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            keyword: this.searchKeyword
                        }
                    });
                    if (response.data.code === 200) {
                        // 过滤掉未启用的试卷
                        const allPapers = response.data.data.list;
                        this.availablePapers = allPapers.filter(paper => paper.status === 1);
                        this.total = response.data.data.total;
                    } else {
                        this.$message.error(response.data.msg);
                    }
                } catch (error) {
                    console.error(error);
                    this.$message.error('获取试卷列表失败');
                }
            },
            // 加载考试记录
            async loadExamRecords() {
                if (!this.user || !this.user.id) {
                    return;
                }
                try {
                    const response = await axios.get('/exam', {
                        params: {
                            operation: 'getExamRecords',
                            userId: this.user.id
                        }
                    });
                    if (response.data.code === 200) {
                        const records = response.data.data;
                        this.examRecords = {};
                        records.forEach(record => {
                            this.examRecords[record.paperId] = record;
                        });
                    } else {
                        this.$message.error(response.data.msg);
                    }
                } catch (error) {
                    console.error(error);
                    this.$message.error('获取考试记录失败');
                }
            },
            // 开始考试
            async startExam(paperId) {
                try {
                    if (!this.user || !this.user.id) {
                        this.$alert('请先登录', '提示', {type: 'warning'});
                        return;
                    }
                    const response = await axios.get('/exam', {
                        params: {
                            operation: 'startExam',
                            paperId: paperId,
                            userId: this.user.id
                        }
                    });
                    if (response.data.code === 200) {
                        if (response.data.msg === '您已参加过此考试') {
                            // 学生已经参加过此考试，显示提示信息
                            this.$alert('您已参加过此考试，不能再次参加。', '提示', {type: 'warning'});
                        } else {
                            // 正常开始考试
                            this.paper = response.data.data;
                            if (!this.paper.questionList || this.paper.questionList.length === 0) {
                                // 如果 questionList 为空，提示错误
                                this.$alert('试卷题目加载失败，请联系管理员。', '错误', {type: 'error'});
                                return;
                            }
                            this.questions = this.paper.questionList;
                            this.initAnswers();
                            this.remainingTime = this.paper.duration * 60; // 转换为秒
                            this.startTimer();
                            this.isExamStarted = true;
                        }
                    } else if (response.data.code === 409) {
                        // 学生已经参加过此考试
                        this.$alert('您已参加过此考试，不能再次参加。', '提示', {type: 'warning'});
                    } else {
                        this.$alert(response.data.msg, '提示', {type: 'warning'});
                    }
                } catch (error) {
                    console.error(error);
                    this.$message.error('开始考试失败');
                }
            },
            // 初始化答案
            initAnswers() {
                this.questions.forEach(question => {
                    this.$set(this.answers, question.questionId, '');
                });
            },
            // 提交考试
            async submitExam() {
                try {
                    clearInterval(this.timerInterval);
                    this.remainingTime = 0; // 将剩余时间设置为0，隐藏倒计时
                    const paperId = this.paper.paperId;
                    const response = await axios.post('/exam?operation=submitExam', {
                        userId: this.user.id,
                        paperId: paperId,
                        answers: this.answers
                    });
                    if (response.data.code === 200) {
                        const result = response.data.data;
                        this.$alert(`考试提交成功！您的得分是：${result.score}分`, '考试结果', {
                            type: 'success',
                            callback: action => {
                                // 重新加载考试记录
                                this.loadExamRecords();
                                this.backToPaperList();
                            }
                        });
                    } else {
                        this.$alert(response.data.msg, '提示', {type: 'warning'});
                    }
                } catch (error) {
                    console.error(error);
                    this.$message.error('提交考试失败');
                }
            },
            // 查看已提交的试卷和答案
            async viewExam(record) {
                try {
                    const response = await axios.get('/exam', {
                        params: {
                            operation: 'getExamDetail',
                            recordId: record.recordId
                        }
                    });
                    if (response.data.code === 200) {
                        const examDetail = response.data.data;
                        this.paper = examDetail.paper;
                        this.questions = this.paper.questionList;
                        this.answers = examDetail.answers || {};
                        const examStatus = examDetail.status;

                        if (examStatus === 'submitted') {
                            // 考试已提交，查看回顾
                            this.isExamStarted = false;
                            this.isExamReview = true;
                        } else if (examStatus === 'in_progress') {
                            // 考试进行中，继续考试
                            this.isExamStarted = true;
                            this.isExamReview = false;
                            // 设置剩余时间（可根据需要从后端获取）
                            this.remainingTime = this.calculateRemainingTime(record);
                            this.startTimer();
                        }
                    } else {
                        this.$message.error(response.data.msg);
                    }
                } catch (error) {
                    console.error(error);
                    this.$message.error('获取试卷详情失败');
                }
            },
            calculateRemainingTime(record) {
                const examDuration = this.paper.duration * 60; // 试卷总时长（秒）
                const startTime = new Date(record.startTime).getTime(); // 考试开始时间
                const currentTime = new Date().getTime(); // 当前时间
                const elapsedTime = Math.floor((currentTime - startTime) / 1000); // 已经过的时间（秒）
                const remainingTime = examDuration - elapsedTime;
                return remainingTime > 0 ? remainingTime : 0;
            },
            // 返回试卷列表
            backToPaperList() {
                this.paper = null;
                this.questions = [];
                this.answers = {};
                this.isExamStarted = false;
                this.isExamReview = false;
                this.remainingTime = 0;       // 重置剩余时间
                clearInterval(this.timerInterval); // 清除计时器
                this.timerInterval = null;    // 重置计时器变量
                this.loadAvailablePapers();   // 重新加载试卷列表
            },
            // 开始倒计时
            startTimer() {
                this.timerInterval = setInterval(() => {
                    this.remainingTime--;
                    if (this.remainingTime <= 0) {
                        clearInterval(this.timerInterval);
                        this.submitExam();
                    }
                }, 1000);
            },
            // 格式化时间
            formatTime(seconds) {
                const m = Math.floor(seconds / 60).toString().padStart(2, '0');
                const s = (seconds % 60).toString().padStart(2, '0');
                return `${m}:${s}`;
            },
            // 获取用户信息
            getUserInfo() {
                const userStr = localStorage.getItem('user');
                if (userStr) {
                    this.user = JSON.parse(userStr);
                } else {
                    this.$alert('请先登录', '提示', {
                        type: 'warning',
                        callback: () => {
                            window.location.href = '/login.html';
                        }
                    });
                }
            },
            // 搜索试卷
            handleSearch() {
                this.currentPage = 1;
                this.loadAvailablePapers();
            },
            // 分页大小改变
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadAvailablePapers();
            },
            // 页码改变
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadAvailablePapers();
            }
        },
        mounted() {
            // 获取用户信息
            this.getUserInfo();
            // 加载考试记录
            this.loadExamRecords();
            // 加载可用试卷列表
            this.loadAvailablePapers();
        }
    });
</script>
</body>
</html>
